<?php

/**
 * Yii Controller CrudController
 *
 * @author nguyenmanhluu
 * @since Aug 8, 2013 - 6:47:20 PM
 */
class CrudController extends MyController
{

    public $modelName    = '';
    public $model        = '';
    public $title        = '';
    public $listColumns  = array();
    public $formColumns  = array();
    public $indexView    = '//_crud/index';
    public $listView     = '//_crud/_list';
    public $formView     = '//_crud/_form';
    public $currentLimit = 10;
    public $ajaxControl  = TRUE;
    public $order        = '';

    public function init()
    {
        parent::init();

        // Thiết lập model dùng chung 
        $this->_setModel();
    }

    protected function _setModel()
    {
        // Tạo model được sử dụng chính trong Controller này
        $pk = isset($_GET['pk']) ? $_GET['pk'] : FALSE;

        $model = $this->modelName;

        if ($model && class_exists($model))
        {
            if ($pk)
            {
                $this->model = call_user_func($model . '::model');
                $this->model = $this->model->findByPk($pk);
                if ($this->model == NULL)
                    throw new CHttpException(400, Yii::t('yii', 'Your request is invalid.'));
            }
            else
                $this->model = new $model;
        }
    }

    public function criteria()
    {
        $rtn        = new CDbCriteria();
        $rtn->order = $this->order;
        return $rtn;
    }

    public function actionIndex()
    {
        $this->checkAccess();

        // Lấy các phương thức của Controller hiện tại
        $controller      = Yii::app()->controller->id;
        $this->pageTitle = Yii::t($controller, ucfirst($controller));

        $model = call_user_func($this->modelName . '::model');

        $criteria        = $this->criteria();
        $count           = $model->count($criteria);
        $pages           = new CPagination($count);
        $pages->route    = $this->route;
        $pages->pageSize = $this->currentLimit;
        $pages->applyLimit($criteria);

        $data = $model->findAll($criteria);
        if (Yii::app()->request->isAjaxRequest)
        {
            $this->layout = '//layouts/ajax';
            $this->render($this->listView, array(
                'data'  => $data,
                'pages' => $pages,
            ));
        }
        else
        {
            $this->render($this->indexView, array(
                'data'  => $data,
                'model' => $this->model,
                'pages' => $pages,
            ));
        }
    }

    public function actionSearch()
    {
        $this->checkAccess();

        $this->pageTitle = Yii::t('main', 'Search');
        $this->actionIndex();
    }

    public function actionView($pk)
    {
        $this->checkAccess();

        $this->pageTitle = Yii::t('main', 'View');
        echo $pk;
    }

    public function actionCreate()
    {
        $this->checkAccess();

        $controller      = Yii::app()->controller->id;
        $this->pageTitle = Yii::t($controller, ucfirst($controller));
        $this->pageTitle .= " / " . Yii::t($controller, 'Create');

        $this->model->setScenario('create');
        $this->form('Create');

        if (Yii::app()->request->isAjaxRequest)
        {
            $cs            = Yii::app()->clientScript;
            $cs->scriptMap = array(
                'jquery.js'               => false,
                'jquery.yiiactiveform.js' => false,
            );
            $this->layout  = '//layouts/ajax';
        }
        $this->render($this->formView, array('model' => $this->model));
    }

    public function actionEdit()
    {
        $this->checkAccess();

        $controller      = Yii::app()->controller->id;
        $this->pageTitle = Yii::t($controller, ucfirst($controller));
        $this->pageTitle .= " / " . Yii::t($controller, 'Edit');

        $this->model->setScenario('edit');
        $this->form('Edit');

        if (Yii::app()->request->isAjaxRequest)
        {
            $cs            = Yii::app()->clientScript;
            $cs->scriptMap = array(
                'jquery.js'               => false,
                'jquery.yiiactiveform.js' => false,
            );
            $this->layout  = '//layouts/ajax';
        }
        $this->render($this->formView, array('model' => $this->model));
    }

    public function actionDelete($pk)
    {
        $this->checkAccess();

        $model     = call_user_func($this->modelName . '::model');
        $delStatus = $model->deleteByPk($pk);

        if (!Yii::app()->request->isAjaxRequest)
        {
            $getParams = $_GET;

            // Nếu trường hợp update thì khi ra ngoài list sẽ bỏ pk đi
            if (isset($getParams['pk']))
            {
                unset($getParams['pk']);
            }
            $this->redirect($this->createUrl(Yii::app()->controller->id . "/index", $getParams));
        }

        if ($delStatus)
        {
            echo json_encode(array(
                'err' => 0,
                'msg' => 'Delete Successful!'
            ));
            return;
        }
        else
        {
            echo json_encode(array(
                'err' => 1,
                'msg' => 'Error, please try again!'
            ));
            return;
        }
    }

    protected function form($action = 'Create')
    {

        // if it is ajax validation request
        if (isset($_POST['ajax']))
        {
            echo CActiveForm::validate($this->model);
            Yii::app()->end();
        }

        // collect user input data
        if (isset($_POST[$this->modelName]))
        {
            $this->model->attributes = $_POST[$this->modelName];
            // validate user input and redirect to the previous page if valid
            if ($this->model->validate())
            {
                if (!$this->save($action))
                {
                    $noti = Yii::t('form', 'Can\'t do {action} , please try again!', array(
                                '{action}' => Yii::t('form', $action)
                    ));
                    Yii::app()->user->setFlash('success', $noti);
                }
                else
                {
                    $noti = Yii::t('form', '{action} successful!', array(
                                '{action}' => Yii::t('form', $action)
                    ));
                    Yii::app()->user->setFlash('success', $noti);

                    // Trường hợp không AJAX thì redirect về trang index
                    if (!Yii::app()->request->isAjaxRequest)
                    {
                        $submit = isset($_POST['submit']) ? $_POST['submit'] : 'return';
                        if ($submit == 'return')
                        {
                            $getParams = $_GET;

                            // Nếu trường hợp update thì khi ra ngoài list sẽ bỏ pk đi
                            if (isset($getParams['pk']))
                            {
                                unset($getParams['pk']);
                            }
                            $this->redirect($this->createUrl(Yii::app()->controller->id . "/index", $getParams));
                        }
                        elseif ($submit == 'continue')
                        {
                            $this->refresh();
                        }
                    }
                }
            }
            else
            {
//                echo CActiveForm::validate($this->model);
            }
        }
    }

    protected function save($action = 'Create')
    {
        return $this->model->save();
    }

}

/** 
 * End file CrudController
 */
